<?php

class NetworkAdmin extends LeftAndMain  {
	private static $url_segment = "network";
	private static $menu_title = "Network";	
	private static $menu_icon = 'network/images/network-icon.png';
	
	private static $allowed_actions = array(
		'root_data',
		'load_data',
		'sponsor_member_detail',
		'build_tree',
		'placement_member_detail'
	);

	public function init() {
		parent::init();
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
		Requirements::javascript(FRAMEWORK_DIR . '/javascript/i18n.js');
		Requirements::add_i18n_javascript('network/javascript/lang');
		Requirements::javascript('network/javascript/NetworkAdmin.min.js');
		Requirements::css('network/css/NetworkAdmin.css');
	}
	
	function Sponsor(){
		return Distributor::get_obj_by_username(Sponsor::get_root_username());
	}
	
	function Placement(){
		return Distributor::get_obj_by_username(Placement::get_root_username());
	}
	
	function root_data(){
		$root_id = $this->Sponsor()->ID;
		if($this->request->getVar('username')){
			$root_id = Distributor::get_id_by_username($this->request->getVar('username'));
		}

		if($root_id){
			$data = array(
				'result' => 'success',
	            'root' => Sponsor::tree_node($root_id)
	        );
		}
		else{
			$data = array(
				'result' => 'error',
	            'msg' => _t('NetworkAdmin.INVALID_MEMBER', 'Invalid member')
	        );
		}
		
        return Convert::array2json($data);
    }
	
	function load_data(){
        if($this->request->getVar('operation') && method_exists($this, $this->request->getVar('operation'))) {
            $this->response->addHeader("Content-Type", "application/json; charset=utf-8");
            $this->response->addHeader("Pragma", "no-cache");
            $this->response->addHeader("Cache-Control", "no-cache, must-revalidate");
            $this->response->setStatusCode(200);
            return $this->{$this->request->getVar('operation')}($this->request->getVar('id'));
        }
        
        $this->response->setStatusCode(404);
    }
	
	function sponsor_member_detail(){
        $current_sponsor = Sponsor::get()->find('MemberID', (int)$this->Sponsor()->ID);
        $sponsor = Sponsor::get()->filter('NLeft:GreaterThanOrEqual', $current_sponsor->NLeft)->filter('NRight:LessThanOrEqual', $current_sponsor->NRight)->find('MemberID', (int)$this->request->getVar('id'));
        if($sponsor){
            $member = Member::get()->byID($sponsor->MemberID);
            $html = '<table class="table table-striped table-bordered">';
            $html .= '<tr><td>'._t('NetworkAdmin.SPONSOR_USERNAME', 'Sponsor Username').'</td><td>'.$member->Sponsor()->Username.'</td></tr>';
            $html .= '<tr><td>'._t('NetworkAdmin.USERNAME', 'Username').'</td><td>'.$member->Username.'</td></tr>';
            $html .= '<tr><td>'._t('NetworkAdmin.JOINED', 'Joined').'</td><td>'.$member->obj('JoinedDate')->Nice().'</td></tr>';
            $html .= '<tr><td>'._t('NetworkAdmin.STATUS', 'Status').'</td><td>'.$member->obj('Status')->Title().'</td></tr>';
            $html .= '<tr><td>'._t('NetworkAdmin.MEMBER_TYPE', 'Member Type').'</td><td>'.$member->RankTitle.'</td></tr>';
            $html .= '<tr><td>'._t('NetworkAdmin.REGISTER_COUNTRY', 'Register Country').'</td><td>'.$member->RegisterCountryTitle.'</td></tr>';
			$html .= '<tr><td>'._t('NetworkAdmin.TOTAL_DIRECT_SPONSOR', 'Total Direct Sponsor').'</td><td>'.$member->obj('TotalSponsorDirectDownline')->Formatted().'</td></tr>';
			$html .= '<tr><td>'._t('NetworkAdmin.TOTAL_SPONSOR_DOWNLINES', 'Total Sponsor Downlines').'</td><td>'.$member->obj('TotalSponsorGroupDownline')->Formatted().'</td></tr>';
			$html .= '</table>';
            return $html;
        }
        
        return _t('NetworkAdmin.INVALID_MEMBER', 'Invalid member');
    }
    
    function Search($username){
        $sponsor = Sponsor::get()->find('MemberID', (int)Distributor::currentUserID());
        $data = array();
		$matchedDownlines = Sponsor::get()->filter('NLeft:GreaterThanOrEqual', $sponsor->NLeft)->filter('NRight:LessThanOrEqual', $sponsor->NRight)->filter('Member.Username:PartialMatch', $username);
		if(!$matchedDownlines){
			return "[]";
		}
		
		$filter = array();
		foreach($matchedDownlines as $item){
			$filter[] = " (Sponsor.NLeft < ".(int)$item->NLeft." AND Sponsor.NRight > ".(int)$item->NRight.") ";
		}
		
		$select = array(
			"`ID`"
		);
		$from = array(
			"`Sponsor`"
		);
		$where = $filter;
		$orderby = '';

		$query = new SQLQuery($select, $from, $where, $orderby);
		$query->setDistinct(true);
		$query->setConnective('OR');
		$result = $query->execute();
		$data = array();
		while($item = $result->next()) { $data[] = "#node_".$item['ID']; }
        return Convert::array2json($data);
    }
    
    function GetChildren($id){
        $sponsor = Sponsor::get()->byID((int)$id);
        if($sponsor){
            $result = array();
            $level = $sponsor->NLevel + 1;
            $children = $sponsor->ChildBranch("NLevel = ".$level);
            foreach($children as $child){
                $result[] = Sponsor::tree_node($child->ID);
            }
            return Convert::array2json($result);
        }
    }
	
	function build_tree(){
        $username = $this->request->getVar('username');

        $id = (int)Distributor::get_id_by_username($username);
        $left = 0;
        $right = 0;
        $placement = DataObject::get_one('Placement', "MemberID = ".(int)$this->Placement()->ID);
        if($placement){
            $left = (int)$placement->NLeft;
            $right = (int)$placement->NRight;
        }

        $data = Placement::get()
        ->filter('NLeft:GreaterThanOrEqual', $left)
        ->filter('NRight:LessThanOrEqual', $right)
        ->find('ID', $id);
		
		if(!$data){
			 return Convert::array2json(array('error' => _t('NetworkAdmin.UNABLE_FIND_TEAM_NETWORK', 'Unable find team network for member username - {username}', '', array('username' => $username))));
		}

        $level = (int)$data->NLevel;
        $left = (int)$data->NLeft;
        $right = (int)$data->NRight;
        $parentid = (int)$data->ParentID;
        $parentusername = ($data->ParentID) ? $data->Parent()->Member()->Username : '';
        $position = (int)$data->NSeqno;
        $showlevel = Placement::get_show_level();
        $maxLevel = $level + $showlevel;
        
        $items = Placement::get()
        ->filter('NLeft:GreaterThanOrEqual', $left)
        ->filter('NRight:LessThanOrEqual', $right)
        ->filter('NLevel:LessThanOrEqual', $maxLevel)
        ->sort(array('NLevel' => 'ASC', 'NSeqno' => 'ASC', 'ID' => 'ASC'));

        $searchResult = array();
        if($items->count()){
            foreach($items as $key => $item){
                if($item->MemberID){
                    $member = $item->Member();
                    $arr_data = array();
                    $arr_data['id'] = $item->ID;
                    $arr_data['level'] = (int)($item->NLevel - $level);
                    $arr_data['parentid'] = (int)$item->ParentID;
                    $arr_data['position'] = (int)$item->NSeqno;
                    $arr_data['distributorid'] = (int)$member->ID;
                    $arr_data['rankcode'] = $member->RankCode;
                    $arr_data['username'] = ($member->Username) ? $member->Username : 'n/a';
					$arr_data['left'] = DBField::create_field('Int', $member->TodayTotalLeftGroupBV)->Formatted();
					$arr_data['right'] = DBField::create_field('Int', $member->TodayTotalRightGroupBV)->Formatted();
                    if(isset($searchResult[$arr_data['level']][$arr_data['parentid']][$arr_data['position']])){
                        continue;
                    }
                    
                    $searchResult[$arr_data['level']][$arr_data['parentid']][$arr_data['position']] = $arr_data;
                }
            }
        }

        $currentcol = 1;
        $child_limit = Placement::get_direct_child_limit();
        $totalcol = 1;
        for ($k = 1; $k < $showlevel; $k++) {
            $totalcol *= $child_limit;
        }
        $table = '';
        $arr_postparentid = array();
        $disabled = '';
        $currentusername = $this->Placement()->Username;
        $currentmemberid = $this->Placement()->ID;
        $currentmemberrankcode = $this->Placement()->RankCode;
		$currentleft = DBField::create_field('Int', $this->Placement()->TodayTotalLeftGroupBV)->Formatted();
		$currentright = DBField::create_field('Int', $this->Placement()->TodayTotalRightGroupBV)->Formatted();
        
        if($username == $currentusername){
            $disabled = "disabled";
            $parentusername = "";
        }
        $table .= '<p><a href="#" rel="tooltip" title="'._t('NetworkAdmin.VIEW_PREVIOUS_LEVEL', 'View previous level of team network').'" id="previous" data-username="'.$parentusername.'" class="btn action '.$disabled.'">'._t('NetworkAdmin.PREVIOUS_LEVEL', 'Previous Level').'</a></p>';
        $table .= '<div class="team-table">';
        $table .= '<table width="100%" class="table table-striped">';
        $table .= '<tbody>';
        if($username != $currentusername){
            $table .= '<tr>';
            $table .= '<td colspan="'.$totalcol.'" class="text-center">';
            $table .= '<div><a class="view_tree" href="#" data-username="'.$currentusername.'"><span class="ui-icon ui-icon-arrowthickstop-1-n" style="display:inline-block; vertical-align: middle;"></span><br><b>'._t('NetworkAdmin.TOP', 'TOP').'</b></a></div>';
            $url = Controller::join_links($this->Link('placement_member_detail'), $currentmemberid);
            $table .= '<a class="member_detail" rel="tooltip" href="'.$url.'" title="'._t('NetworkAdmin.VIEW_MEMBER_DETAILS', 'Click here to view member details {username}', '', array('username' => $currentusername)).'" data-title="'._t('NetworkAdmin.MEMBER_DETAILS', 'Member Details').'" data-username="'.$currentusername.'"><img src="'.$this->RankImageURL($currentmemberrankcode).'" width="36" height="45" border="0"><br>'.$currentusername.'</a>';
            $table .= '<p>'._t('NetworkAdmin.POINT', 'Left: {left} | Right: {right}', '', array('left' => $currentleft, 'right' => $currentright)).'</p>';
            $table .= '<p>.</p>';
			$table .= '<p><a class="view_tree" href="#" data-username="'.$parentusername.'"><span class="ui-icon ui-icon-arrowthickstop-1-n" style="display:inline-block; vertical-align: middle;"></span></a></p>';
            $table .= '</td>';
            $table .= '</tr>';
        }
        for ($i = 0; $i < $showlevel; $i++) {
            $parentkey = 0;
            $arr_parentid = array();
            $arr_data_by_level = isset($searchResult[$i]) ? $searchResult[$i] : array();
            $colspan = $totalcol/$currentcol;
            $table .= '<tr class="team_level'.$i.'">';
            $currentparentid = 0;
			$currentposition = 0;
            for ($j = 1; $j <= $currentcol; $j++) {
                $arr_data = array();
                if($i == 0){
                    $arr_data = isset($arr_data_by_level[$parentid][$position]) ? $arr_data_by_level[$parentid][$position] : array();
                }
                else{
                	$currentposition += 1;
					
                    if(isset($arr_postparentid[$parentkey]) && $currentparentid = (int)$arr_postparentid[$parentkey]){
                        if(isset($arr_data_by_level[$currentparentid][$currentposition])){
                            $arr_data = $arr_data_by_level[$currentparentid][$currentposition];
                        }
                    }
                    
                    if($currentposition >= $child_limit){
                        $parentkey += 1;
                    }
                }
                if(sizeof($arr_data)){
                    $table .= '<td colspan="'.$colspan.'" class="text-center">';
                    $distributorid = $arr_data['distributorid'];
                    $url = Controller::join_links($this->Link('placement_member_detail'), $distributorid);
                    $table .= '<a class="member_detail" rel="tooltip" href="'.$url.'" title="'._t('NetworkAdmin.VIEW_MEMBER_DETAILS', 'Click here to view member details {username}', '', array('username' => $arr_data['username'])).'" data-title="'._t('NetworkAdmin.MEMBER_DETAILS', 'Member Details').'" data-username="'.$arr_data['username'].'"><img src="'.$this->RankImageURL($arr_data['rankcode']).'" width="36" height="45" border="0"><br>'.$arr_data['username'].'</a>';
					$table .= '<br>'._t('NetworkAdmin.POINT', 'Left: {left} | Right: {right}', '', array('left' => $arr_data['left'], 'right' => $arr_data['right']));
					if($i+1 == $showlevel){
						$table .= '<br><a class="view_tree" href="#" data-username="'.$arr_data['username'].'"><span class="ui-icon ui-icon-arrowthickstop-1-s" style="display:inline-block; vertical-align: middle;"></span></a>';
					}
                    $table .= "</td>";
                        
                    $arr_parentid[] = $arr_data['id'];
                }
                else{
                    $table .= '<td colspan="'.$colspan.'" class="text-center">';
                    $table .= '<img src="'.$this->RankImageURL('empty').'" width="36" height="45" border="0">';
                    $table .= '</td>';
                    
                    $arr_parentid[] = 0;
                }

				if(!($j % $child_limit)){
                	$currentposition = 0;
				}
            }
            $table .= '</tr>';
            $currentcol *= $child_limit;
            $arr_postparentid = $arr_parentid;
        }
        $table .= '</tbody>';
        $table .= '</table>';
        $table .= '</div>';
        
        return Convert::array2json(array('result' => $table));
    }

	function placement_member_detail(){
        $current_placement = Placement::get()->find('MemberID', (int)$this->Placement()->ID);
        $placement = Placement::get()->filter('NLeft:GreaterThanOrEqual', $current_placement->NLeft)->filter('NRight:LessThanOrEqual', $current_placement->NRight)->find('MemberID', (int)$this->request->param('ID'));
        if($placement){
            $member = Member::get()->byID($placement->MemberID);
            $html = '<table class="table table-striped table-bordered">';
            $html .= '<tr><td>'._t('NetworkAdmin.SPONSOR_USERNAME', 'Sponsor Username').'</td><td colspan="2">'.$member->Sponsor()->Username.'</td></tr>';
            $html .= '<tr><td>'._t('NetworkAdmin.USERNAME', 'Username').'</td><td colspan="2">'.$member->Username.'</td></tr>';
            $html .= '<tr><td>'._t('NetworkAdmin.JOINED', 'Joined').'</td><td colspan="2">'.$member->obj('JoinedDate')->Nice().'</td></tr>';
            $html .= '<tr><td>'._t('NetworkAdmin.STATUS', 'Status').'</td><td colspan="2">'.$member->obj('Status')->Title().'</td></tr>';
            $html .= '<tr><td>'._t('NetworkAdmin.MEMBER_TYPE', 'Member Type').'</td><td colspan="2">'.$member->RankTitle.'</td></tr>';
            $html .= '<tr><td>'._t('NetworkAdmin.REGISTER_COUNTRY', 'Register Country').'</td><td colspan="2">'.$member->RegisterCountryTitle.'</td></tr>';
			$html .= '<tr><th></th><th class="text-right">'._t('NetworkAdmin.LEFT', 'Left').'</th><th class="text-right">'._t('NetworkAdmin.RIGHT', 'Right').'</th></tr>';
			$html .= '<tr><td>'._t('NetworkAdmin.ACCUMULATE_GROUP_BV', 'Accumulate Group BV').'</td><td class="text-right">'.DBField::create_field('Int', $member->AccumulateLeftGroupBV)->Formatted().'</td><td class="text-right">'.DBField::create_field('Int', $member->AccumulateRightGroupBV)->Formatted().'</td></tr>';
			$html .= '<tr><td>'._t('NetworkAdmin.TODAY_GROUP_BV', 'Today Group BV').'</td><td class="text-right">'.DBField::create_field('Int', $member->TodayLeftGroupBV)->Formatted().'</td><td class="text-right">'.DBField::create_field('Int', $member->TodayRightGroupBV)->Formatted().'</td></tr>';
			$html .= '<tr><td>'._t('NetworkAdmin.CF_GROUP_BV', 'C/F Group BV').'</td><td class="text-right">'.DBField::create_field('Int', $member->CarryLeftGroupBV)->Formatted().'</td><td class="text-right">'.DBField::create_field('Int', $member->CarryRightGroupBV)->Formatted().'</td></tr>';
			$html .= '<tr class="success"><td>'._t('NetworkAdmin.TODAY_TOTAL_GROUP_BV', 'Today Total Group BV').'</td><td class="text-right">'.DBField::create_field('Int', $member->TodayTotalLeftGroupBV)->Formatted().'</td><td class="text-right">'.DBField::create_field('Int', $member->TodayTotalRightGroupBV)->Formatted().'</td></tr>';
			$html .= '<tr><td>'._t('NetworkAdmin.TOTAL_TEAM_MEMBERS', 'Total Team Members').'</td><td class="text-right">'.$member->obj('TotalPlacementLeftGroupDownline')->Nice().'</td><td class="text-right">'.$member->obj('TotalPlacementRightGroupDownline')->Nice().'</td></tr>';
			$html .= '</table>';
            return $html;
        }
        
        return _t('NetworkAdmin.INVALID_MEMBER', 'Invalid member');
    }

	function RankImageURL($rankcode){
        $theme_dir = sprintf('%s/images/placement/', SSViewer::get_theme_folder());
        $icon = $rankcode ? sprintf('%s_icon.png', strtolower($rankcode)) : 'unknow_icon.png';
        if(Director::fileExists($theme_dir.$icon)){
            return $theme_dir.$icon;
        }
		else if(Director::fileExists('network/images/placement/'.$icon)){
			return 'network/images/placement/'.$icon;
		}
		else{
			if(Director::fileExists($theme_dir.'unknow_icon.png')){
	            return $theme_dir.'unknow_icon.png';
	        }
			else {
				return 'network/images/placement/unknow_icon.png';
			}
		}
    }
}